package com.est.dase.query;

import java.util.ArrayList;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
/**
 *
 * @author Fernando Geraldes, Jaime Santos, Jorge Silva
 *
 */
public class GetContacts {

	public static ArrayList<String> listName;
	public static ArrayList<String> listNumber;

	private Activity activity;
	private boolean status=false;

	public GetContacts(Activity activity){
		this.activity=activity;
	}

	public String[] getContact(){
		listName = new ArrayList<String>();
		listNumber = new ArrayList<String>();
		String[] contacts = null;
		ArrayList<String> list = new ArrayList<String>();
		String pdata = null;
		String pName = null;
		ContentResolver cr = activity.getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
				null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
		if (cur.getCount() > 0) {
			while (cur.moveToNext()){
				String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));{
					if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
						Cursor pCur = cr.query(
								ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
								null, 
								ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+id, 
								null, null);

						while (pCur.moveToNext()) {
							pdata = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
							pName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
							listName.add(pName);
							listNumber.add(pdata);
							if(pdata != null && pName != null){
								String contact = pName + " " + pdata;
								list.add(contact);
							}
						} 
						pCur.close();
					}
				}
			}
			cur.close();
		}
		contacts = new String[list.size()];
		for(int i=0; i<list.size(); i++){
			contacts[i] = list.get(i);
		}
		status = true;
		return contacts;
	}

	public boolean isStatus() {
		return status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

}
